import {Student, StudentFormData} from "./types.ts";
import Database, {QueryResult} from "@tauri-apps/plugin-sql";

/**
 * lastInsertId	最后插入行的 ID	所有方法
 * rowsAffected	受影响的行数	Tauri-plugin-sql
 * changes	受影响的行数	SQLite WASM
 * lastInsertRowid	最后插入行的 ID	SQLite WASM/Raw
 */
class StudentsService {
    /**
     * 查询所有学生
     */
    async getAllStudents(): Promise<Student[]> {
        try {
            const db = await Database.load("sqlite:test.db")
            return await db.select<Student[]>("SELECT * FROM students");
        } catch (err) {
            console.error("获取学生列表失败:", err);
            throw new Error("获取学生列表失败，请稍后重试");
        }
    }

    /**
     * 添加学生
     * @param student
     */
    async createStudent(student: StudentFormData): Promise<QueryResult> {
        try {
            const db = await Database.load("sqlite:test.db");

            return await db.execute("INSERT INTO students (name, student_id,birthday,class) VALUES ($1, $2,$3,$4)", [
                student.name, student.student_id, student.birthday, student.class
            ])
        } catch (error) {
            console.error("添加学生失败:", error);
            throw new Error("添加学生失败，请检查输入");
        }
    }

    async updateStudent(student: Student) {
        console.log("update studentservice")
        try {
            const db = await Database.load("sqlite:test.db");

            const result= await db.execute("UPDATE students SET name=$1,student_id = $2,birthday=$3,class=$4 where id= $5", [
                student.name, student.student_id, student.birthday, student.class, student.id
            ])

            return result.rowsAffected

        } catch (error) {
            console.error("更新学生失败:", error);
            throw new Error("更新学生失败，请检查输入");
        }
    }

    async deleteStudent(id: number) {
        try {
            const db = await Database.load("sqlite:test.db");

         const result:QueryResult =await db.execute("DELETE FROM students WHERE id = ?", [
                id
            ])
            return result.rowsAffected
        } catch (error) {
            console.error("删除学生失败:", error);
            throw new Error("删除学生失败，请重试");
        }
    }


}

export const studentsService = new StudentsService();